﻿using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;

namespace StackExchangeRedisTest
{
    class Program
    {
        private static readonly RedisService RedisService = new RedisService();

        static void Main(string[] args)
        {
            //TestStringSetAndGet();

            TestPubSub();
        }

        /// <summary>
        /// 测试Redis发布订阅
        /// </summary>
        private static void TestPubSub()
        {
            var action = new Action<string>(Console.WriteLine);
            //订阅
            var channel = "beyondhost";
            RedisService.Subscribe(channel, action);
            while (true)
            {
                //发布消息到channel
                RedisService.Publish(channel, $"当前时间：{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
                Thread.Sleep(1000);
            }
        }


        /// <summary>
        /// 测试Redis字符串存取，10秒过期
        /// </summary>
        private static void TestStringSetAndGet()
        {
            var key = "hello";
            var value = "I'm here...";
            var expireSeconds = 10;

            Console.WriteLine($"正在写入字符串 key:{key} value:{value} expireSeconds:{expireSeconds}");
            if (RedisService.Set(key, value, expireSeconds))
            {
                while (true)
                {
                    var nowValue = RedisService.Get(key);
                    Console.WriteLine($"{RedisService.KeySecondsToLive(key)}秒后消失 {nowValue}");
                    Thread.Sleep(1000);
                }
            }
        }
    }
}
